package com.jdbc.lesson03;

import com.jdbc.utils.JdbcUtils;

import java.sql.*;
import java.util.Date;

public class TestInsert {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        int i = 0;
        try {
            conn =  JdbcUtils.getConnection();
            //PreparedStatement和Statement的区别
            //使用?展位符代替参数
            String sql = "INSERT INTO `users`(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) values(?,?,?,?,?)";
            st = conn.prepareStatement(sql);//预编译SQL，先写sql,不执行
            //手动给参数赋值
            //setInt(参数下标,参数值)
            st.setInt(1,5);//id
            st.setString(2,"jack");//name
            st.setString(3,"999999");//password
            st.setString(4,"jack@qq.com");//email
            //注意点：sql.Date
            //       util.Date
            //setDate(int parameterIndex, java.sql.Date x) 形参列表：参数下标,java.sql.Date类型的日期
            // new Date().getTime() 获得时间戳
            st.setDate(5,new java.sql.Date(new Date().getTime()));//birthday

            //执行sql语句 st = conn.prepareStatement(sql);进行预编译，调用st.executeUpdate()不用传入sql
            i = st.executeUpdate();
            if(i > 0){
                System.out.println("插入数据成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}
